from utils import AddDay, CalDay
from fastapi import APIRouter
from datetime import datetime
from models import FineInfo, db, BorrowInfo, FineQuery
fine_router = APIRouter()

'''
updateFine统计更新罚金
通过遍历borrow_info集合，寻找超过应还日期且归还状态为false的借阅信息
如果罚款信息已存在，则更新应缴金额，如果不存在，则新建罚款信息
返回值：msg——是否有罚款信息更新的信息
'''


@fine_router.get('/updateFine', summary='统计更新罚金', tags=["罚款管理相关接口"])
async def updateFine():
    msg = "小朋友们都交罚款了"
    now = datetime.now()
    today = now.strftime("%Y-%m-%d")
    # TODO  delete this mock day
    mock_today = AddDay(today, 30)
    today = mock_today
    print("mock today:", today)
    for x in db.borrow_info.find():
        x = BorrowInfo(**x)
        if x.return_status == False:
            if CalDay(x.due_date, today).days > 0:
                Cal_date = CalDay(x.due_date, today).days
                if db.fine_info.find_one({"book_id": x.book_id, "handle_status": False}):
                    db.fine_info.update_one({"book_id": x.book_id, "handle_status": False}, {
                                            "$set": {"need_pay": round(Cal_date*0.5, 2)}})
                else:
                    fine = {}
                    fine["book_id"] = x.book_id
                    fine["book_name"] = x.book_name
                    fine["card_id"] = x.card_id
                    fine["reader_name"] = x.reader_name
                    fine["borr_date"] = x.borr_date
                    fine["due_date"] = x.due_date
                    fine["need_pay"] = round(Cal_date*0.5, 2)
                    fine["paid_in"] = 0.00
                    fine["handle_status"] = False
                    db.fine_info.insert_one(fine)
                    # 首次生成罚款信息的同时，将借阅卡的可用状态改为False
                    db.cards.update_one({"card_id": x.card_id}, {
                                        "$set": {"available_status": False}})
                msg = "还有小朋友没交罚款"
    return {"msg": msg}

'''
payFine缴纳罚款
参数：payment……缴纳金额、book_id——书本编号
变量：current_need——剩余应缴
如果缴纳的金额大于等于应缴金额，则返回“罚款已全部缴纳”并返回找零；如果缴纳罚金未达到应缴数目，返回“缴费成功，罚款尚未全额缴纳”
返回值：msg——相关信息、change——找零
'''


@fine_router.get('/payFine', summary='缴纳罚款', tags=["罚款管理相关接口"])
async def payFine(payment: float, book_id: str):
    msg = '缴纳成功'
    success = False
    change = 0.00
    fine = db.fine_info.find_one({"book_id": book_id, "handle_status": False})
    if fine:
        borrow = db.borrow_info.find_one(
            {"book_id": book_id, "return_status": False})
        if borrow:
            fine = FineInfo(**fine)
            current_need = fine.need_pay-fine.paid_in
            if payment >= current_need:
                db.fine_info.update_one({"book_id": book_id, "handle_status": False}, {
                                        "$set": {"paid_in": fine.need_pay, "handle_status": True}})
                db.cards.update_one({"card_id": fine.card_id}, {
                                    "$set": {"available_status": True}})
                change = payment-current_need
                success = True
                msg = '罚款已全额缴纳'
            else:
                db.fine_info.update_one({"book_id": book_id, "handle_status": False}, {
                                        "$set": {"paid_in": fine.paid_in+payment}})
                success = True
                msg = '缴费成功，罚款尚未全额缴纳'
        else:
            msg = '没有找到对应的借阅信息'
    else:
        msg = '没有找到该书的罚款信息'
    return {"msg": msg, "success": success, "change": change}


@fine_router.post('/queryFineInfo', summary='查阅罚款信息', tags=["罚款管理相关接口"])
async def queryFineInfo(fine: FineQuery):
    page = fine.page
    size = fine.size
    skip = size * (page - 1)
    # Get Key
    query_condition = {}
    for condition in fine:
        con_key = condition[0]
        con_value = condition[1]
        if con_key not in ['size', 'page']:  # 筛去非必要参数
            if con_value in [False, True, None]:  # 处理Bool值，不用正则
                if con_value != None:  # None值不参与条件查询
                    query_condition[con_key] = con_value
            else:  # str用正则模糊查询
                query_condition[con_key] = {'$regex': con_value}

    print("query_condition", query_condition)
    # 返回数据总条数
    dataCount = db.fine_info.find(query_condition).count()
    res = db.fine_info.find(query_condition).limit(size).skip(skip)
    finelist = []
    for it in res:
        fineData = FineInfo(**it)
        if hasattr(fineData, 'id'):
            delattr(fineData, 'id')
        fineData.need_pay = round(fineData.need_pay, 2)
        fineData.paid_in = round(fineData.paid_in, 2)
        finelist.append(fineData)
    return {'data': finelist, 'data_count': dataCount}
